package oldcode;

import java.util.ArrayList;
import java.util.List;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.curator.x.discovery.ServiceDiscovery;
import org.apache.curator.x.discovery.ServiceDiscoveryBuilder;
import org.apache.curator.x.discovery.details.JsonInstanceSerializer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.to8to.kitt.esb.ZkConfig;
import com.to8to.kitt.utils.LogUtils;

public class ServiceReporter {

	public static Logger logger = LoggerFactory.getLogger(ServiceReporter.class);  
	
	private ZkConfig zkConfig;
	
	private int heartbeanIntervalsMs = 5000;
	
	CuratorFramework client = null;
	
	ServiceDiscovery<String> serviceDiscovery;
	
	List<AbstractMonitor> monitors = new ArrayList<AbstractMonitor>();
	
	public ServiceReporter(ZkConfig zkConfig)
	{
		this.zkConfig = zkConfig;
		init();
	}
	
	public ZkConfig getZkConfig() {
		return zkConfig;
	}

	public void init()
	{
		client = CuratorFrameworkFactory.newClient(zkConfig.zkhosts,
				zkConfig.sessionTimeoutMs, zkConfig.connectionTimeoutMs,
				new ExponentialBackoffRetry(zkConfig.baseSleepTimeMs, zkConfig.maxRetries));

		client.start();
		
		serviceDiscovery = ServiceDiscoveryBuilder.builder(String.class).client(client)
				.serializer(new JsonInstanceSerializer<String>(String.class)).basePath(zkConfig.servicePath).build();
		
		try {
			serviceDiscovery.start();
		} catch (Exception e) {
			logger.error(LogUtils.logStackTrace(e));
		}
	}
	
	public void addMonitor(AbstractMonitor m)
	{
		monitors.add(m);
	}
	
	public void startReport()
	{
        while(true)
        {
        	for(AbstractMonitor m : monitors)
        	{
        		logger.debug("detect on: " + m.getClass().getSimpleName());
        		try {
        			m.runOnce(serviceDiscovery);
        		} catch (Exception e) {
        			logger.error(LogUtils.logStackTrace(e));
        		}
        	}
	        try {
				Thread.sleep(heartbeanIntervalsMs);
			} catch (InterruptedException e) {
				logger.error(LogUtils.logStackTrace(e));
			}
        }
	}
	
	

	public int getHeartbeanIntervalsMs() {
		return heartbeanIntervalsMs;
	}

	public void setHeartbeanIntervalsMs(int heartbeanIntervalsMs) {
		this.heartbeanIntervalsMs = heartbeanIntervalsMs;
	}

	public static void main(String[] args) 
	{	
		
	}

}
